package com.douhao.personal.service.impl;

import com.douhao.personal.mapper.UserMapper;
import com.douhao.personal.model.RoleUserBo;
import com.douhao.personal.model.User;
import com.douhao.personal.model.UserRole;
import com.douhao.personal.model.UserRoleBo;
import com.douhao.personal.service.UserService;
import com.douhao.personal.util.Constants;
import com.douhao.personal.util.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    protected final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    UserMapper userMapper;

    @Override
    public User selectById(String id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public User login(String email, String pswd) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("email", email);
        map.put("pswd", pswd);
        return userMapper.login(map);
    }

    @Override
    public Page<User> pageList(User user, int pageNo, int pageSize) {
        Page<User> page = new Page<>(pageNo, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Constants.CODE_PAGE_START, page.getFirst());
        map.put(Constants.CODE_PAGE_SIZE, pageSize);
        map.put("user", user);//封装查询条件
        List<User> userList = userMapper.list(map);
        long count = userMapper.count(map);
        page.setResult(userList);
        page.setTotalCount(count);
        return page;
    }

    @Override
    public Map<String, Object> deleteUserById(String ids) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            int count = 0;
            String[] idArray = new String[]{};
            if (StringUtils.contains(ids, ",")) {
                idArray = ids.split(",");
            } else {
                idArray = new String[]{ids};
            }

            for (String id : idArray) {
                count += this.deleteByPrimaryKey(new Long(id));
            }
            resultMap.put("status", 200);
            resultMap.put("count", count);
        } catch (Exception e) {
            logger.debug("根据IDS删除用户出现错误，ids[%s]", getClass());
            resultMap.put("status", 500);
            resultMap.put("message", "删除出现错误，请刷新后再试！");
        }
        return resultMap;
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Page<UserRoleBo> findUserAndRole(UserRoleBo userRoleBo, int pageNo, int pageSize) {
        Page<UserRoleBo> page = new Page<>(pageNo, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Constants.CODE_PAGE_START, page.getFirst());
        map.put(Constants.CODE_PAGE_SIZE, pageSize);
        map.put("userRoleBo", userRoleBo);//封装查询条件
        List<UserRoleBo> userRoleList = userMapper.findUserAndRole(map);
        long count = userMapper.userAndRoleCount(map);
        page.setResult(userRoleList);
        page.setTotalCount(count);
        return page;
    }

    @Override
    public List<RoleUserBo> selectRoleByUserId(String id) {
        return userMapper.selectRoleByUserId(id);
    }

    @Override
    public Map<String, Object> addRole2User(String userId, String ids) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        int count = 0;
        try {
            //先删除原有的。
            userMapper.deleteByUserId(userId);
            //如果ids,role 的id 有值，那么就添加。没值象征着：把这个用户（userId）所有角色取消。
            if (StringUtils.isNotBlank(ids)) {
                String[] idArray = null;

                //这里有的人习惯，直接ids.split(",") 都可以，我习惯这么写。清楚明了。
                if (StringUtils.contains(ids, ",")) {
                    idArray = ids.split(",");
                } else {
                    idArray = new String[]{ids};
                }
                //添加新的。
                for (String rid : idArray) {
                    //这里严谨点可以判断，也可以不判断。这个{@link StringUtils 我是重写了的}
                    if (StringUtils.isNotBlank(rid)) {
                        UserRole entity = new UserRole(Long.valueOf(userId), new Long(rid));
                        count += userMapper.insertSelective(entity);
                    }
                }
            }
            resultMap.put("status", 200);
            resultMap.put("message", "操作成功");
        } catch (Exception e) {
            resultMap.put("status", 200);
            resultMap.put("message", "操作失败，请重试！");
        }
        //清空用户的权限，迫使再次获取权限的时候，得重新加载
        //TokenManager.clearUserAuthByUserId(userId);
        //resultMap.put("count", count);
        return resultMap;
    }

    @Override
    public Map<String, Object> deleteRoleByUserIds(String userIds) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String[] idArray = null;
        try {
            if (StringUtils.contains(userIds, ",")) {
                idArray = userIds.split(",");
            } else {
                idArray = new String[]{userIds};
            }
            for (String userId : idArray) {
                userMapper.deleteByUserId(userId);
            }

            // userMapper.deleteRoleByUserIds(userIds);
            resultMap.put("status", 200);
            resultMap.put("message", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("status", 200);
            resultMap.put("message", "操作失败，请重试！");
        }
        return resultMap;
    }

    @Override
    public int updateByPrimaryKeySelective(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

}
